package nrpc.message;

import java.lang.reflect.Type;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;

import message.AbstractMessageParser;
import message.MessageParser;
import message.reflect.HandlerMapper;
import nrpc.message.meta.ReturnMessage;

public class ReturnMessageParser extends AbstractMessageParser{
	
	public ReturnMessageParser(ReturnMessage obj, HandlerMapper mapper, Type type) {
		super(obj);
		this.messageParser = mapper.getParserSupplier(type).parse(obj.get());
		this.label = obj.getLabel();
	}
	
	private MessageParser messageParser;
	private int label;
	private int step = 0;
	@Override
	public boolean write(ByteBuffer byteBuffer) {
		switch(step){
		case 0:
			try {
				byteBuffer.putInt(this.label);
			} catch (BufferOverflowException e) {
				return false;
			}
			step++;
		case 1:
			if(!(messageParser.write(byteBuffer))) return false;
			step++;
		}
		return true;
	}

}
